#!/bin/sh

#
# Test the SHA-256 check when write files to a FAT file system.
#

. "$(cd "$(dirname "$0")" && pwd)/common.sh"

cat >$CONFIG <<EOF
define(BOOT_PART_OFFSET, 63)
define(BOOT_PART_COUNT, 77238)

file-resource 1K.bin {
	host-path = "${TESTFILE_1K}"
}

mbr mbr-a {
    partition 0 {
        block-offset = \${BOOT_PART_OFFSET}
        block-count = \${BOOT_PART_COUNT}
        type = 0xc # FAT32
        boot = true
    }
}
task complete {
	on-init {
                mbr_write(mbr-a)
                fat_mkfs(\${BOOT_PART_OFFSET}, \${BOOT_PART_COUNT})
        }
        on-resource 1K.bin {
                fat_write(\${BOOT_PART_OFFSET}, "1K.bin")
        }
}
EOF

# Create the firmware file
$FWUP_CREATE -c -f $CONFIG -o $FWFILE

# Now be sneaking and replace the data file with a same-sized imposter
unzip -q $FWFILE -d $UNZIPDIR
cp $TESTFILE_1K_CORRUPT $UNZIPDIR/data/1K.bin
cd $UNZIPDIR
zip -q $WORK/imposter.fw meta.conf data/1K.bin
cd -
echo Expecting Blake2b mismatch during apply...
if $FWUP_APPLY -a -d $IMGFILE -i $WORK/imposter.fw -t complete; then
    echo "This should have failed"
    exit 1
fi

echo Expecting Blake2b mismatch during verification...
if $FWUP_VERIFY -V -i $WORK/imposter.fw; then
    echo "This should have failed"
    exit 1
fi
